//
//  WBOAuthController.swift
//  SinaWeibo
//
//  Created by 风不会停息 on 2016/11/15.
//  Copyright © 2016年 风不会停息. All rights reserved.
//

import UIKit
import SVProgressHUD
let plistPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")
class WBOAuthController: UIViewController {

    let web = UIWebView()
    override func loadView() {
        
        self.view = web
        web.delegate = self
     
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = #colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1)
        //返回按钮的设置
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imageName: nil, target: self, action: #selector(close))
        
        //懒人按钮的设置
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "懒人键", imageName: nil, target: self, action: #selector(lazyMan))
        //加载登录界面
        loadOAuthorPage()
        
    }

    //懒人模式
    @objc private func lazyMan(){
        let jsString = "document.getElementById('userId').value = '523923719@qq.com', document.getElementById('passwd').value = 'lcr123456'"
        web.stringByEvaluatingJavaScript(from: jsString)
        
    }
    //加载到授权页面
    @objc private func loadOAuthorPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + "2483618679" + "&redirect_uri=" + "http://www.baidu.com"
        let url = URL(string: urlString)
        let req = URLRequest(url: url!)
        web.loadRequest(req)
        
    }
    
    @objc private func close(){
        self.dismiss(animated: true, completion: nil)
    }
    

    deinit {
        print("销毁", #line, #function)
    }
    
    
    
    
   

}
//将代理方法抽取到分类中执行，模块的功能独立化
extension WBOAuthController:UIWebViewDelegate
{
    //指示器的加载和移除
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
        SVProgressHUD.dismiss()
    }
     //获取到code
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.url?.absoluteString ?? ""
        let flag = "code="
        if urlString.contains(flag) {
            let query = request.url?.query ?? ""
            let code = (query as NSString).substring(from: flag.characters.count)
//            print(code)
            
            WBUserAccountViewModel.WBUserAccountShared.loadAccessToken(code: code, finished: {(isSuccess:Bool) -> () in
                
                if !isSuccess{
                    
                    SVProgressHUD.showError(withStatus: "失败了")
                    print("没有成功")
                    return
                }
                //如果用dismiss completion里面没有发送通知切换根视图控制器的话，会返回modal之前的控制器，也就是tabbar控制器
                self.dismiss(animated: true, completion: {
                      NotificationCenter.default.post(name: NSNotification.Name(kChoseRootViewController), object: "mjjj")
                })

  
            })
            
            
            return false
        }
        return true
    }
    
    
   
}
